package cn.agiledata.bank.linkbank.action;

import java.io.IOException;
import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import cn.agiledata.bank.common.util.Constant;
import cn.agiledata.bank.common.util.DateUtil;
import cn.agiledata.bank.common.util.ForeDict;
import cn.agiledata.bank.common.util.WeatherUtil;
import cn.agiledata.bank.linkbank.exception.LinkBankException;
import cn.agiledata.bank.linkbank.logic.payment.UnsPayResponse;
import cn.agiledata.bank.linkbank.service.WebPayService;
import com.vnv.infrastructure.action.IPBBaseAction;
import com.vnv.infrastructure.exception.IPBException;
import com.vnv.infrastructure.logic.IPBAppFactory;

/**
 * @author jianglei
 * 
 */
public class UnsPayResponseAction extends IPBBaseAction {
    public static final String UNSPAYRESPONSE_KEY = "unsPayResponse";

    /**
     * 允许未登录调用
     */
    public int hasAccessPermission(int accessLevel, HttpServletRequest request)
            throws IPBException {
        return 1;
    }

    public ActionForward unsPayResponse(ActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        UnsPayResponse unsPayResponse = (UnsPayResponse) request
                .getAttribute(UNSPAYRESPONSE_KEY);
        HttpSession session = request.getSession();
        if (unsPayResponse == null) {
            unsPayResponse = (UnsPayResponse) session
                    .getAttribute(UNSPAYRESPONSE_KEY);
            // zln 修正 增加银行编号返回项目
            unsPayResponse.setBankCode("unspay");
            request.setAttribute(UNSPAYRESPONSE_KEY, unsPayResponse);
        }
        session.removeAttribute(UNSPAYRESPONSE_KEY);
        if (unsPayResponse == null) {
            throw LinkBankException.LOSE_RESPONSE_DATA;
        }
        request.setAttribute("pageResponse", Boolean.FALSE); // 默认页面不反馈
        if (unsPayResponse.isInner()) { // 内部交易无需进行mac拼装
            int responseMode = unsPayResponse.getResponseMode();
            if ((responseMode & Constant.RESPONSE_MODE_PAGE) == Constant.RESPONSE_MODE_PAGE) {
                boolean sessionTimeout = WeatherUtil.sessionIsTimeout(request);
                // 内部交易若session过期，则不跳转到返回页面
                request.setAttribute("pageResponse", Boolean
                        .valueOf(!sessionTimeout));
            }
            request.setAttribute("responseMode", String.valueOf(responseMode));
        } else {// 非内部交易需进行mac值拼装
            WebPayService webPayService = (WebPayService) IPBAppFactory
                    .getObj(ForeDict.SERVICE_WEB_PAY);
            int responseMode = unsPayResponse.getResponseMode();
            if ((responseMode & Constant.RESPONSE_MODE_PAGE) == Constant.RESPONSE_MODE_PAGE) {
                String mac = webPayService.generateMac(unsPayResponse,
                        Constant.RESPONSE_MODE_PAGE);
                request.setAttribute("mac", mac);
                String sign = webPayService.generateSign(unsPayResponse, Constant.RESPONSE_MODE_PAGE);
                request.setAttribute("sign", sign);
                request.setAttribute("responseMode", String
                        .valueOf(Constant.RESPONSE_MODE_PAGE));
                request.setAttribute("pageResponse", Boolean.TRUE);
            }
            if ((responseMode & Constant.RESPONSE_MODE_BACKGROUND) == Constant.RESPONSE_MODE_BACKGROUND) {
                try {
                    webPayService.backgroundResponse(unsPayResponse);
                } catch (IOException e) {
                    if (unsPayResponse.isSuccessful()
                            || unsPayResponse.isPaid()) {
                        String returnMessage = getAppExceptionMessage(request,
                                LinkBankException.REACHLESS_RESPONSE);
                        log.error(returnMessage);
                        /* zln 修正 20080529 商户选择前、后台都响应方式时，如果后台响应失败，
                           此处设置的returnMessage会导致前台的mac值加密内容变化，而使页面响应的mac校验出现错误，
                           此处取消returnMessage的返回 */
                        e.printStackTrace();
                    }
                }
            }
        }
        Calendar c = Calendar.getInstance();
        int ms = c.get(Calendar.MILLISECOND);
        System.out.println("========== Date of response to merchant: "
                + DateUtil.date2String(c.getTime(),
                        DateUtil.DATE_FORMAT_DATE_TIME) + "." + ms);
        return mapping.findForward(FORWARD_SUCCESS);
    }

}
